package com.jee.ssm.common.utils.hik;

import com.jee.ssm.common.exception.ApiException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketTimeoutException;


public class HttpUtil {

	private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

	private static final int CONNECT_TIME_OUT = 10000;

	private static final int SOCKET_TIME_OUT = 100000;

	/**
	 * http post请求
	 *
	 * @param url
	 * @param postData
	 * @return string
	 * @throws Exception
	 */
	public static String doPost(String url, String postData) {
		CloseableHttpClient httpclient = HttpClients.custom().build();
//		log.debug("httpClient::url【{}】::data【{}】",url,postData);
		HttpPost httpPost = new HttpPost(url);
		StringEntity postEntity = new StringEntity(postData, "UTF-8");
		httpPost.addHeader("Content-Type", "application/json");
		httpPost.setEntity(postEntity);
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(SOCKET_TIME_OUT)
				.setConnectTimeout(CONNECT_TIME_OUT).build();
		// 设置请求器的配置
		httpPost.setConfig(requestConfig);
		try {
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
//			log.info("返回状态:【{}】", response.getStatusLine().getStatusCode());
			String returnData = EntityUtils.toString(entity, "UTF-8");
//			log.debug("httpClient::url【{}】::returnData【{}】",url,returnData);
			return returnData;
		} catch (ConnectionPoolTimeoutException e) {
			throw new ApiException("Http post ConnectionPoolTimeoutException", e);
		} catch (ConnectTimeoutException e) {
			throw new ApiException("Http post ConnectTimeoutException", e);
		} catch (SocketTimeoutException e) {
			throw new ApiException("Http post SocketTimeoutException", e);
		} catch (Exception e) {
			log.error("其他异常,",e);
			throw new ApiException("Http post other Exception " + e.getMessage() + " ", e);
		} finally {
			httpPost.abort();
		}
	}

}
